package com.szml.user.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author limin
 * @date 2025-06-20 10:39
 * @description
 */
@Configuration
public class MyBatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        // 配置分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql"); // 数据库方言
        properties.setProperty("reasonable", "true");     // 分页合理化
        pageInterceptor.setProperties(properties);

        // 设置插件（注意这里只需要设置一次）
        factoryBean.setPlugins(new Interceptor[]{pageInterceptor});

        // 设置mapper.xml位置（您重复设置了两次，保留一个即可）
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));

        // 添加类型别名包扫描
        factoryBean.setTypeAliasesPackage("com.szml.user.entity");

        return factoryBean.getObject(); // 注意这里返回的是SqlSessionFactory而不是SqlSessionFactoryBean
}
}
